package GreedyAlgorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class Code05 {

    public int[][] merge(int[][] intervals) {

        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] > o2[0])
                    return 1;
                else if (o1[0] < o2[0])
                    return -1;
                else {
                    return Integer.compare(o1[1], o2[1]);
                }
            }
        });

        System.out.println("intervals = " + Arrays.deepToString(intervals));

        ArrayList<int[]> answer = new ArrayList<>();
        for (int i = 0; i < intervals.length; i++) {
            int[] nums = new int[2];
            nums[0] = intervals[i][0];
            nums[1] = intervals[i][1];
            for (int j = i+1; j < intervals.length; j++) {
                if (intervals[j][0] > nums[1]){
                    i = j-1;
                    break;
                }else {
                    nums[1] = Math.max(nums[1],intervals[j][1] );
                    i=j;
                }
            }
            answer.add(nums);
        }

        return answer.toArray(new int[answer.size()][]);
    }

    public static void main(String[] args) {
        Code05 code05 = new Code05();
//        System.out.println("code05.merge(new int[][]{{1,3},{2,6},{8,10},{15,18}}) = " + Arrays.deepToString(code05.merge(new int[][]{{2, 6},{1, 3}, {15, 18}, {8, 10}})));
//        System.out.println("code05.merge(new int[][]{{1,3},{2,6},{8,10},{15,18}}) = " + Arrays.deepToString(code05.merge(new int[][]{{1,4},{4,5}})));
//        System.out.println("code05.merge(new int[][]{{1,4},{1,5}}) = " + Arrays.deepToString(code05.merge(new int[][]{{1,4},{1,5}})));
        System.out.println("code05.merge(new int[][]{{1,4},{2,3}}) = " + Arrays.deepToString(code05.merge(new int[][]{{1,4},{2,3}})));
    }

}
